<template>
	<div id="url-picture-upload">
		<!-- URL输入区域 -->
		<div class="upload-section">
			<div class="input-wrapper">
				<a-input
					v-model:value="fileUrl"
					placeholder="请输入图片链接"
					@keyup.enter="handleUpload"
					class="url-input"
					:disabled="loading || props.uploading"
				>
					<template #prefix>
						<LinkOutlined class="input-icon" />
					</template>
				</a-input>
			</div>
			<a-button
				type="primary"
				:loading="loading || props.uploading"
				:size="props.size"
				@click="handleUpload"
				class="upload-btn"
			>
				<template #icon>
					<UploadOutlined v-if="!loading && !props.uploading" />
				</template>
				{{ props.buttonText }}
			</a-button>
		</div>

		<!-- 图片预览操作区域 -->
		<div class="preview-actions" v-if="props.pictureUrl || props.value">
			<div class="preview-info">
				<CheckCircleOutlined class="success-icon" />
				<span class="success-text">图片已上传</span>
			</div>
			<div class="action-buttons">
				<a-button type="text" size="small" @click="previewImage" class="preview-btn" v-if="!imageLoadError">
					<template #icon>
						<EyeOutlined />
					</template>
					预览
				</a-button>
			</div>
		</div>

		<!-- 自定义图片预览弹窗 -->
		<div v-if="previewVisible" class="custom-image-preview-overlay" @click="previewVisible = false">
			<div class="custom-preview-container" @click.stop>
				<div class="preview-header">
					<span class="preview-title">图片预览</span>
					<button class="close-btn" @click="previewVisible = false">
						<CloseOutlined />
					</button>
				</div>
				<div class="preview-image-container">
					<div class="image-wrapper" @click="toggleFullscreen">
						<img
							:src="props.pictureUrl || props.value"
							alt="预览图片"
							class="preview-image"
							:class="{ 'fullscreen': isFullscreen }"
							@error="onImageError"
						/>
						<div class="image-overlay">
							<div class="overlay-content">
								<EyeOutlined class="fullscreen-icon" />
								<span class="fullscreen-text">{{ isFullscreen ? '退出全屏' : '全屏查看' }}</span>
							</div>
						</div>
					</div>
				</div>
			</div>
		</div>

		<!-- 无图片时的提示信息 -->
		<div class="tips" v-if="!props.pictureUrl && !props.value">
			<p class="tip-text">
				<InfoCircleOutlined class="tip-icon" />
				支持 JPG、PNG、GIF、WebP 格式，建议使用稳定的图床服务
			</p>
		</div>
	</div>
</template>

<script lang="ts" setup>
import { ref } from 'vue'
import { message } from 'ant-design-vue'
// 导入所需图标
import {
	LinkOutlined,
	UploadOutlined,
	EyeOutlined,
	InfoCircleOutlined,
	CheckCircleOutlined,
	CloseOutlined,
} from '@ant-design/icons-vue'
// 导入上传接口（保持原有接口引用）
import { uploadPictureByUrl } from '@/api/userController'

// 组件Props定义
interface Props {
	pictureUrl?: string // 图片URL
	onSuccess?: (newPictureUrl: string) => void // 上传成功回调
	value?: string // 双向绑定值
	uploading?: boolean // 上传状态
	buttonText?: string // 按钮文本
	size?: string // 按钮尺寸
}

// Props默认值
const props = withDefaults(defineProps<Props>(), {
	buttonText: '上传',
	size: 'default',
})

// 组件事件定义
const emit = defineEmits<{
	'update:value': [value: string] // 更新值的双向绑定事件
	'update:uploading': [uploading: boolean] // 更新上传状态的事件
}>()

// 响应式变量
const fileUrl = ref<string>() // 输入的图片链接
const loading = ref<boolean>(false) // 本地加载状态
const imageLoadError = ref<boolean>(false) // 图片加载错误状态
const previewVisible = ref<boolean>(false) // 预览Modal显示状态
const isFullscreen = ref<boolean>(false) // 全屏状态

/**
 * 处理图片上传逻辑
 * 1. 验证输入链接
 * 2. 调用上传接口
 * 3. 处理成功/失败状态
 * 4. 同步状态到父组件
 */
const handleUpload = async () => {
	if (!fileUrl.value) {
		message.warning('请输入图片链接')
		return
	}

	// 开始上传，更新状态
	loading.value = true
	emit('update:uploading', true)

	try {
		// 调用上传接口
		const params = { fileUrl: fileUrl.value as string }
		const res = await uploadPictureByUrl(params)

		// 处理接口响应
		if (res.data.code === 0 && res.data.data) {
			message.success('图片上传成功')
			props.onSuccess?.(res.data.data) // 触发成功回调
			emit('update:value', res.data.data) // 更新双向绑定值
			fileUrl.value = '' // 清空输入框
			imageLoadError.value = false // 重置错误状态
		} else {
			message.error('图片上传失败，' + res.data.message)
		}
	} catch (error: any) {
		console.error('图片上传失败', error)
		message.error('图片上传失败：' + error.message)
	} finally {
		// 结束上传，恢复状态
		loading.value = false
		emit('update:uploading', false)
	}
}

/**
 * 处理图片加载失败
 * 1. 标记错误状态
 * 2. 提示用户
 */
const onImageError = () => {
	imageLoadError.value = true
	message.error('图片加载失败，请检查链接是否有效')
}

/**
 * 处理图片预览
 * 1. 验证图片URL有效性
 * 2. 显示预览Modal
 */
const previewImage = () => {
	const imageUrl = props.pictureUrl || props.value
	if (imageUrl && !imageLoadError.value) {
		previewVisible.value = true
	}
}

/**
 * 切换全屏状态
 */
const toggleFullscreen = () => {
	isFullscreen.value = !isFullscreen.value
}
</script>

<style scoped lang="scss">
#url-picture-upload {
	margin-bottom: 16px;

	// 上传区域样式（保持原有设计）
	.upload-section {
		display: flex;
		gap: 12px;
		align-items: stretch;
		margin-bottom: 16px;

		.input-wrapper {
			flex: 1;
			min-width: 0; // 防止flex子元素溢出

			.url-input {
				height: 40px; // 与按钮高度一致
				border-radius: 8px;
				transition: all 0.3s ease;
				font-size: 14px;
				border: 1px solid #d9d9d9;
				background: #ffffff;
				display: flex;
				align-items: center;

				&:hover {
					border-color: #4096ff;
					box-shadow: 0 0 0 2px rgba(64, 150, 255, 0.1);
				}

				&:focus-within {
					border-color: #4096ff;
					box-shadow: 0 0 0 2px rgba(64, 150, 255, 0.2);
					outline: none;
				}

				.input-icon {
					color: #8c8c8c;
					font-size: 14px;
				}

				// 修复Input内部垂直居中
				:deep(.ant-input) {
					height: 38px;
					line-height: 38px;
					padding: 0 11px;
					border: none;
					box-shadow: none;
					background: transparent;
					display: flex;
					align-items: center;
				}

				:deep(.ant-input-prefix) {
					margin-right: 8px;
					display: flex;
					align-items: center;
				}

				:deep(.ant-input::placeholder) {
					line-height: 38px;
					vertical-align: middle;
				}

				:deep(.ant-input-group-wrapper) {
					border: none;
				}
			}
		}

		.upload-btn {
			min-width: 120px;
			height: 40px; // 与输入框高度一致
			border-radius: 8px;
			display: flex;
			align-items: center;
			justify-content: center;
			gap: 6px;
			transition: all 0.3s ease;
			font-size: 14px;
			font-weight: 500;
			flex-shrink: 0; // 防止按钮被压缩

			&:hover {
				transform: translateY(-1px);
				box-shadow: 0 4px 12px rgba(24, 144, 255, 0.3);
			}

			&:active {
				transform: translateY(0);
			}
		}
	}

	// 预览操作区域样式（保持原有设计）
	.preview-actions {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 8px 12px;
		background: #f6ffed;
		border: 1px solid #b7eb8f;
		border-radius: 6px;
		margin-top: 8px;
		transition: all 0.3s ease;

		.preview-info {
			display: flex;
			align-items: center;
			gap: 6px;

			.success-icon {
				color: #52c41a;
				font-size: 14px;
			}

			.success-text {
				color: #389e0d;
				font-size: 12px;
				font-weight: 500;
			}
		}

		.action-buttons {
			display: flex;
			gap: 4px;

			.preview-btn {
				color: #1890ff;
				font-size: 12px;
				padding: 0 8px;
				height: 24px;

				&:hover {
					background: rgba(24, 144, 255, 0.1);
					color: #096dd9;
				}
			}
		}
	}

	// 提示信息样式（保持原有设计）
	.tips {
		margin-top: 8px;

		.tip-text {
			display: flex;
			align-items: center;
			gap: 8px;
			color: #8c8c8c;
			font-size: 12px;
			margin: 0;
			padding: 8px 12px;
			background: #f9f9f9;
			border-radius: 6px;
			border-left: 3px solid #1890ff;

			.tip-icon {
				color: #1890ff;
			}
		}
	}

	// 响应式：移动端（≤768px）（保持原有设计）
	@media (max-width: 768px) {
		.upload-section {
			flex-direction: column;
			gap: 12px;

			.input-wrapper .url-input {
				height: 44px;

				:deep(.ant-input) {
					height: 42px;
					line-height: 42px;
					font-size: 16px;
				}
			}

			.upload-btn {
				width: 100%;
				height: 44px;
				font-size: 16px;
				min-width: unset;
			}
		}

		.preview-actions {
			flex-direction: column;
			gap: 8px;
			align-items: stretch;

			.preview-info {
				justify-content: center;
			}

			.action-buttons {
				justify-content: center;
				gap: 12px;
			}
		}
	}

	// 响应式：中等屏幕（769px-1024px）（保持原有设计）
	@media (max-width: 1024px) and (min-width: 769px) {
		.upload-section {
			gap: 10px;

			.upload-btn {
				min-width: 110px;
			}
		}
	}
}

// 自定义图片预览弹窗样式
.custom-image-preview-overlay {
	position: fixed;
	top: 0;
	left: 0;
	width: 100vw;
	height: 100vh;
	background: rgba(0, 0, 0, 0.6);
	display: flex;
	align-items: center;
	justify-content: center;
	z-index: 1000;
	backdrop-filter: blur(4px);
	animation: fadeIn 0.2s ease-out;
}

.custom-preview-container {
	position: relative;
	background: #fff;
	border-radius: 12px;
	box-shadow: 0 8px 32px rgba(0, 0, 0, 0.2);
	overflow: hidden;
	max-width: 90vw;
	max-height: 90vh;
	animation: scaleIn 0.2s ease-out;
}

.preview-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 16px 20px;
	border-bottom: 1px solid #f0f0f0;
	background: #fafafa;
}

.preview-title {
	font-size: 16px;
	font-weight: 600;
	color: #262626;
	margin: 0;
}

.close-btn {
	width: 32px;
	height: 32px;
	border: none;
	background: transparent;
	border-radius: 6px;
	cursor: pointer;
	display: flex;
	align-items: center;
	justify-content: center;
	color: #8c8c8c;
	transition: all 0.2s;
	font-size: 14px;

	&:hover {
		background: #f5f5f5;
		color: #262626;
	}

	&:active {
		transform: scale(0.95);
	}
}

.preview-image-container {
	padding: 20px;
	display: flex;
	align-items: center;
	justify-content: center;
	min-width: 300px;
	min-height: 300px;
	max-width: 80vw;
	max-height: 70vh;

	.image-wrapper {
		position: relative;
		cursor: pointer;
		border-radius: 8px;
		overflow: hidden;
		transition: all 0.3s ease;

		&:hover {
			.image-overlay {
				opacity: 1;
			}
		}

		.preview-image {
			max-width: 300px;
			max-height: 300px;
			width: auto;
			height: auto;
			object-fit: contain;
			border-radius: 8px;
			box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
			transition: all 0.3s ease;

			&.fullscreen {
				max-width: 90vw;
				max-height: 90vh;
				width: auto;
				height: auto;
				cursor: zoom-out;
			}
		}

		.image-overlay {
			position: absolute;
			top: 0;
			left: 0;
			right: 0;
			bottom: 0;
			background: rgba(0, 0, 0, 0.5);
			display: flex;
			align-items: center;
			justify-content: center;
			opacity: 0;
			transition: opacity 0.3s ease;
			border-radius: 8px;

			.overlay-content {
				display: flex;
				flex-direction: column;
				align-items: center;
				gap: 8px;
				color: white;
				text-align: center;

				.fullscreen-icon {
					font-size: 24px;
				}

				.fullscreen-text {
					font-size: 14px;
					font-weight: 500;
				}
			}
		}
	}
}

@keyframes fadeIn {
	from {
		opacity: 0;
	}
	to {
		opacity: 1;
	}
}

@keyframes scaleIn {
	from {
		transform: scale(0.9);
		opacity: 0;
	}
	to {
		transform: scale(1);
		opacity: 1;
	}
}

// 移动端适配
@media (max-width: 768px) {
	.custom-preview-container {
		max-width: 95vw;
		max-height: 95vh;
		margin: 10px;
	}

	.preview-header {
		padding: 12px 16px;
	}

	.preview-title {
		font-size: 14px;
	}

	.close-btn {
		width: 28px;
		height: 28px;
		font-size: 12px;
	}

	.preview-image-container {
		padding: 16px;
		min-width: 250px;
		min-height: 250px;
		max-width: 90vw;
		max-height: 60vh;
	}
}
</style>
